﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace EzDeploy.Core
{
    public class DeployGridItemBinder : IDeployGridItemBinder
    {
        readonly BindingSource _bindingSource;

        List<DeployGridItem> _original;
        List<DeployGridItem> _current;

        public List<DeployGridItem> GetValue()
        {
            return _current?? new List<DeployGridItem>();
        }

        public void SetValue(List<DeployGridItem> value)
        {
            _original = value;
            _current = _original.ToList();
        }

        public void Bind()
        {
            _bindingSource.DataSource = _current;
        }

        public void Bind(Predicate<DeployGridItem> filter)
        {
            if (_original != null)
            {
                _current = _original.FindAll(filter);
                _bindingSource.DataSource = _current;
            }
            else
            {
                _current = null;
                _bindingSource.DataSource = _current;
            }
        }

        public void Reset()
        {
            if (_original != null)
            {
                foreach (var deployGridItem in _original) // reset
                {
                    if (deployGridItem.ItemStatus != VersionStatus.Unknown && deployGridItem.DeploymentType == DeploymentType.Exclude)
                        deployGridItem.DeploymentType = DeploymentType.Include;
                }

                if(_current != null && _current.Count!=_original.Count)
                    _current = _original.ToList();
            }
            else
                _current = null;
        }

        public DeployGridItemBinder(BindingSource bindingSource)
        {
            _bindingSource = bindingSource;
        }
    }
}
